<!--
 * @Author: your name
 * @Date: 2022-01-27 22:44:43
 * @LastEditTime: 2022-01-27 22:53:44
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \算法测试\day0906\2047.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /**
 * @param {string} sentence
 * @return {number}
 */
        var countValidWords = function (sentence) {
            const n = sentence.length;
            let l = 0, r = 0;
            let ret = 0;
            while (true) {
                while (l < n && sentence[l] === ' ') {
                    l++;
                }
                if (l >= n) {
                    break;
                }
                r = l + 1;
                while (r < n && sentence[r] != ' ') {
                    r++;
                }
                if (isValid(sentence.slice(l, r))) { // 判断根据空格分解出来的 token 是否有效
                    ret++;
                }
                l = r + 1;
            }
            return ret;
        };

        const isValid = (word) => {
            const n = word.length;
            let hasHyphens = false;
            for (let i = 0; i < n; i++) {
                if (word[i] >= '0' && word[i] <= '9') {
                    return false;
                } else if (word[i] === '-') {
                    if (hasHyphens === true || i === 0 || i === n - 1 || !isLetter(word[i - 1]) || !isLetter(word[i + 1])) {
                        return false;
                    }
                    hasHyphens = true;
                } else if (word[i] === '!' || word[i] === '.' || word[i] === ',') {
                    if (i !== n - 1) {
                        return false;
                    }
                }
            }
            return true;
        }

        const isLetter = (ch) => {
            if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
                return true;
            }
            return false;
        }
    </script>
</body>

</html>